package com.grj.boot.util;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.baomidou.mybatisplus.extension.service.IService;
import lombok.Data;

import java.util.List;

@Data
public class TListener implements ReadListener {
    private static final int BATCH_COUNT = 10000;
    private List<Object> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private IService service;

    public TListener(IService service) {
        this.service = service;
    }

    @Override
    public void invoke(Object object, AnalysisContext context) {
        cachedDataList.add(object);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
    }

    private void saveData() {
        service.saveOrUpdateBatch(cachedDataList);
    }
}